package com.lzl.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzl.eduservice.client.VodClient;
import com.lzl.eduservice.entity.EduVideo;
import com.lzl.eduservice.mapper.EduVideoMapper;
import com.lzl.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-03-30
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    //注入VodClient 实习跨服务调用
    @Autowired
    private VodClient vodClient;

    //根据课程id删除小节
    //TODO 删除小节 还需要删除对应的视频文件
    @Override
    public void removeVideoByCourseId(String courseId) {
        //根据课程id  查询出所有的 视频id
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        //List<EduVideo> eduVideoList = baseMapper.selectList(wrapperVideo);
        //然后对eduVideoList 进行遍历取 视频id 放到一个新的集合中

        //优化直接 查询出视频id就行，不需要查出所有的数据
        //select 视频id  from 表名  where id=...
        //wrapperVideo.select("video_source_id") 能查询指定字段
        wrapperVideo.select("video_source_id");
        List<EduVideo> eduVideoList = baseMapper.selectList(wrapperVideo);

        //List<EduVideo> 需要变成 List<String>
        List<String> videoIds = new ArrayList<>();
        for (EduVideo eduVideo : eduVideoList) {
            if(!StringUtils.isEmpty(eduVideo.getVideoSourceId())){
                videoIds.add(eduVideo.getVideoSourceId());
            }
        }
        if(videoIds.size()>0){
            //根据多个视频id删除多个视频
            vodClient.deleteBatch(videoIds);
        }

        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);

    }

    /**
     * 根据小节id-删除小节 和小节里上传的视频
     * @param videoId
     * @return
     */
    @Override
    public void deleteVideoById(String videoId) {

        //根据小节id获取视频id
        EduVideo eduVideo = baseMapper.selectById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
        //判断小节里面是否有视频id
        if(!StringUtils.isEmpty(videoSourceId)){
            //deleteAlyVideo()  是根据视频的id删除 上传视频
            vodClient.deleteAlyVideo(videoSourceId);
        }
        //删除小节
        baseMapper.deleteById(videoId);

    }
}
